package com.example.my_gobang.api;

import com.example.my_gobang.game.MatchRequest;
import com.example.my_gobang.game.MatchResponse;
import com.example.my_gobang.game.Matcher;
import com.example.my_gobang.game.OnlineUserManager;
import com.example.my_gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-08-20
 * Time:13:39
 */
@Component
public class MatchAPI extends TextWebSocketHandler {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private Matcher matcher;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        try {
            // 获取用户信息
            User user = (User) session.getAttributes().get("user");
            // 验证登录
            if (onlineUserManager.getFromGameHall(user.getUserid()) != null
                    || onlineUserManager.getFromGameRoom(user.getUserid()) != null) {
                // 说明当前用户已经登录
                MatchResponse response = new MatchResponse();
                response.setOk(false);
                response.setReason("repeat connection!");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                session.close();
                return;
            }
            // 添加用户在线信息
            onlineUserManager.enterGameHall(user.getUserid(), session);
            System.out.println("玩家" + user.getUsername() + "进入游戏大厅");
        } catch (NullPointerException e) {
            System.out.println("[MatchAPI.afterConnectionEstablished] 当前用户未登录！");
//            e.printStackTrace();
            // 构造响应
            MatchResponse response = new MatchResponse();
            response.setOk(false);
            response.setReason("您尚未登录，请先登录！");

            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //实现处理开始匹配和停止匹配的请求
        User user = (User) session.getAttributes().get("user");
        //获取客户端发来的数据
        String payload = message.getPayload();
        MatchRequest request = objectMapper.readValue(payload, MatchRequest.class);
        MatchResponse response = new MatchResponse();
        if (request.getMessage().equals("startMatch")) {
            // 进入匹配队列
            matcher.add(user);
            response.setOk(true);
            response.setMessage("startMatch");
        } else if (request.getMessage().equals("stopMatch")) {
            // 退出匹配队列
            matcher.remove(user);
            response.setOk(true);
            response.setMessage("stopMatch");
        } else {
            // 非法情况
            response.setOk(false);
            response.setReason("非法的请求！");
        }
        //返回响应
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        try {
            // 获取用户信息
            User user = (User) session.getAttributes().get("user");
            WebSocketSession tmpSession = onlineUserManager.getFromGameHall(user.getUserid());
            if (tmpSession == session) {
                // 删除用户在线信息
                onlineUserManager.exitGameHall(user.getUserid());
            }
            // 若玩家正在匹配中，但是websocket连接断开了，则退出匹配队列
            matcher.remove(user);
        } catch (NullPointerException e) {
            System.out.println("[MatchAPI.handleTransportError] 当前用户未登录！");
//            e.printStackTrace();
            // 构造响应
//            MatchResponse response = new MatchResponse();
//            response.setOk(false);
//            response.setReason("您尚未登录！不能进行匹配！");
//
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        try {
            // 获取用户信息
            User user = (User) session.getAttributes().get("user");
            WebSocketSession tmpSession = onlineUserManager.getFromGameHall(user.getUserid());
            if (tmpSession == session) {
                // 删除用户在线信息
                onlineUserManager.exitGameHall(user.getUserid());
            }
            // 若玩家正在匹配中，但是websocket连接断开了，则退出匹配队列
            matcher.remove(user);
        } catch (NullPointerException e) {
            System.out.println("[MatchAPI.afterConnectionClosed] 当前用户未登录！");
//            e.printStackTrace();
            // 构造响应
//            MatchResponse response = new MatchResponse();
//            response.setOk(false);
//            response.setReason("您尚未登录！不能进行匹配！");
//
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }

    }
}
